import copy
from utils.conf import Response
from rest_framework.views import APIView
from ChatGPTServer.settings import formatResponseData, _request
import json


class Wxredcover(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = []
    # 局部(本视图有效)权限类
    permission_classes = []

    def post(self, request, *args, **kwargs):
        """
        wxredcover接口
        """
        data = copy.deepcopy(formatResponseData)
        try:
            question = request.data.get("question")

            # 异常拦截
            if not question:
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            # 获取token
            r = _request.get("https://gpt.wxredcover.cn/")
            timeStamp = r.text.split('src="/js/index.')[1].split('.js"')[0]
            r = _request.get(f"https://gpt.wxredcover.cn/js/index.{timeStamp}.js")
            token = r.text.split('sk-')[1].split('"')[0]
            token = f"sk-{token}"

            # wxredcover爬虫
            headers = {
                'Content-Type': 'application/json',
                'authorization': f'Bearer {token}',
                'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
            }

            requestData = {
                "model": "gpt-3.5-turbo",
                "messages": [
                    {
                        "role": "user",
                        "content": question
                    }
                ]
            }

            response = _request.post(headers=headers, url='https://ng.wxredcover.cn/v1/chat/completions',
                                     data=json.dumps(requestData))

            answer = response.json()["choices"][0]["message"]["content"]

            data["data"]["answer"] = answer
            return Response(data=data, loggerMsg=f"wxredcover接口响应成功：question={question}")

        except Exception as e:
            return Response(data=data, loggerMsg=f"wxredcover接口响应失败：{e}", isError=True)
